package com.colorful.insuranceproject.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.View;


import com.colorful.insuranceproject.R;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import widget.OnWheelScrollListener;
import widget.WheelView;
import widget.adapters.NumericWheelAdapter;

/**
 * Created by lovely3x on 15-8-7.
 * 选择日期的对话框
 * 没有时间 只有日期 例如 2014 10 10
 */
public class ChoiceDateDialog extends DialogFragment implements View.OnClickListener {
    public static final String ARGUMENT_YEAR = "argument.year";
    public static final String ARGUMENT_MONTH = "argument.month";
    public static final String ARGUMENT_DAY = "argument.day";

    public static final String EXTRA_YEAR = "extra.year";
    public static final String EXTRA_MONTH = "extra.month";
    public static final String EXTRA_DAY = "extra.day";

    public static final String EXTRA_MAX_YEAR = "extra.max.year";
    public static final String EXTRA_MAX_MONTH = "extra.max.month";
    public static final String EXTRA_MAX_DAY = "extra.max.day";

    private static final String TAG = "ChoiceDateDialog";
    final int MAX_YEAR;
    final int MIN_YEAR;
    final int MAX_MONTH;
    final int MIN_MONTH;
    final int MIN_DAY = 1;
    final int MAX_DAY = 31;
    private final Calendar gregorianCalendar;
    private Dialog mDialog;
    private WheelView year;
    private WheelView month;
    private WheelView day;

    private OnChoiceStateChangedListener mOnChoicedListener;
    private Activity mActivity;

    private int defaultYear;
    private int defaultMonth;
    private int defaultDay;
    private NumericWheelAdapter yearAdapter;
    private NumericWheelAdapter monthAdapter;
    private NumericWheelAdapter dayAdapter;

    public ChoiceDateDialog() {
        gregorianCalendar = GregorianCalendar.getInstance();
        MAX_YEAR = gregorianCalendar.get(Calendar.YEAR);
        MIN_YEAR = 2000;
        MAX_MONTH = 12;
        MIN_MONTH = 1;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        this.mActivity = getActivity();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.mActivity = activity;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        mDialog = new Dialog(mActivity, R.style.transparentDialog);
        mDialog.setContentView(R.layout.dialog_choice_date);

        Calendar calendar = Calendar.getInstance();

        Bundle bundle = getArguments();
        if (bundle != null) {
            defaultYear = bundle.getInt(ARGUMENT_YEAR, calendar.get(Calendar.YEAR));
            defaultMonth = bundle.getInt(ARGUMENT_MONTH, calendar.get(Calendar.MONTH) + 1);
            defaultDay = bundle.getInt(ARGUMENT_DAY, calendar.get(Calendar.DAY_OF_MONTH));
        }

        if (savedInstanceState != null) {
            defaultYear = savedInstanceState.getInt(EXTRA_YEAR, calendar.get(Calendar.YEAR));
            defaultMonth = savedInstanceState.getInt(EXTRA_MONTH, calendar.get(Calendar.MONTH) + 1);
            defaultDay = savedInstanceState.getInt(EXTRA_DAY, calendar.get(Calendar.DAY_OF_MONTH));
        }

        initViews();
        return mDialog;
    }

    private void initViews() {
        //init year
        year = (WheelView) mDialog.findViewById(R.id.wv_dialog_choice_date_year);
        yearAdapter = new NumericWheelAdapter(mActivity, MIN_YEAR, MAX_YEAR, "%d 年");
        yearAdapter.setItemResource(R.layout.view_date_choicer_content);
        yearAdapter.setItemTextResource(R.id.tv_view_date_choicer_content);
        year.setViewAdapter(yearAdapter);
        year.setCyclic(true);
        year.addScrollingListener(new YearScrollChangedListener());
//
        //init month
        month = (WheelView) mDialog.findViewById(R.id.wv_dialog_choice_date_month);
        monthAdapter = new NumericWheelAdapter(mActivity, MIN_MONTH, MAX_MONTH, "%d 月");
        monthAdapter.setItemResource(R.layout.view_date_choicer_content);
        monthAdapter.setItemTextResource(R.id.tv_view_date_choicer_content);
        month.setViewAdapter(monthAdapter);
        month.setCyclic(true);
        month.addScrollingListener(new MonthScrollChangedListener());
//
        //init day
        day = (WheelView) mDialog.findViewById(R.id.wv_dialog_choice_date_day);
        dayAdapter = new NumericWheelAdapter(mActivity, MIN_DAY, MAX_DAY, "%d 日");
        dayAdapter.setItemResource(R.layout.view_date_choicer_content);
        dayAdapter.setItemTextResource(R.id.tv_view_date_choicer_content);
        day.setViewAdapter(dayAdapter);
        day.setCyclic(true);
//
        mDialog.findViewById(R.id.tv_dialog_choice_sex_choice).setOnClickListener(this);
        mDialog.setCanceledOnTouchOutside(true);
        mDialog.setCancelable(true);

        day.post(new Runnable() {
            @Override
            public void run() {
                day.setCurrentItem(Math.max(defaultDay - MIN_DAY, 0));
            }
        });
        month.post(new Runnable() {
            @Override
            public void run() {
                month.setCurrentItem(Math.max(defaultMonth - MIN_MONTH, 0));
            }
        });
        year.post(new Runnable() {
            @Override
            public void run() {
                year.setCurrentItem(Math.max(defaultYear - MIN_YEAR, 0));
            }
        });
    }


    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(EXTRA_YEAR, Integer.parseInt(yearAdapter.getItemText(year.getCurrentItem()).toString()));
        outState.putInt(EXTRA_MONTH, Integer.parseInt(monthAdapter.getItemText(month.getCurrentItem()).toString()));
        outState.putInt(EXTRA_DAY, Integer.parseInt(dayAdapter.getItemText(day.getCurrentItem()).toString()));
    }

    @Override
    public void onCancel(DialogInterface dialog) {
        super.onCancel(dialog);
        Log.i(TAG, "onCancel");
        if (mOnChoicedListener != null) {
            mOnChoicedListener.onChoiceCancel();
        }
    }

    public void setOnChoiceChangedListener(OnChoiceStateChangedListener listener) {
        mOnChoicedListener = listener;
    }

    /**
     * 刷新月中的日
     *
     * @param year  年
     * @param month 月
     */
    public void refreshDays(int year, int month) {
        Log.i(TAG, "calc before: year == " + year + "    month == " + month + "  day == 1");
        gregorianCalendar.set(year, month - 1, 1);
        Log.i(TAG, "calc after: year == " + gregorianCalendar.get(Calendar.YEAR) + "    month == " + (gregorianCalendar.get(Calendar.MONTH) + 1) + "     day == " + gregorianCalendar.get(Calendar.DAY_OF_MONTH));
        final int maxDay = gregorianCalendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        NumericWheelAdapter dayAdapter = new NumericWheelAdapter(mActivity, MIN_DAY, maxDay, "%d 日");
        dayAdapter.setItemResource(R.layout.view_date_choicer_content);
        dayAdapter.setItemTextResource(R.id.tv_view_date_choicer_content);
        day.setCyclic(true);
        day.setViewAdapter(dayAdapter);
        gregorianCalendar.setTime(new Date());
    }

    @Override
    public void onClick(View v) {
        dismiss();
        if (mOnChoicedListener != null) {
            int year = ((NumericWheelAdapter) this.year.getViewAdapter()).getValue(this.year.getCurrentItem());
            int month = ((NumericWheelAdapter) this.month.getViewAdapter()).getValue(this.month.getCurrentItem());
            int day = ((NumericWheelAdapter) this.day.getViewAdapter()).getValue(this.day.getCurrentItem());
            gregorianCalendar.set(year, month - 1, day);
            long millisecond = gregorianCalendar.getTime().getTime();
            mOnChoicedListener.onDateChoiced(year, month, day, millisecond);
            gregorianCalendar.setTime(new Date());
        }
    }

    /**
     * 用户选择状态变化监听器
     */
    public interface OnChoiceStateChangedListener {
        /**
         * 用户取消选择了
         */
        void onChoiceCancel();

        /**
         * 当用户选择了之后执行
         *
         * @param year  年份
         * @param month 月份
         * @param day   日器
         */
        void onDateChoiced(int year, int month, int day, long millisecond);
    }

    /**
     * 年份滚动变化监听器
     */
    private class YearScrollChangedListener implements OnWheelScrollListener {

        @Override
        public void onScrollingStarted(WheelView wheel) {

        }

        @Override
        public void onScrollingFinished(WheelView wheel) {
            int intYear = ((NumericWheelAdapter) wheel.getViewAdapter()).getValue(wheel.getCurrentItem());
            int intMonth = ((NumericWheelAdapter) month.getViewAdapter()).getValue(month.getCurrentItem());
            refreshDays(intYear, intMonth);
        }
    }

    /**
     * 月份滚动变化监听器
     */
    private class MonthScrollChangedListener implements OnWheelScrollListener {
        @Override
        public void onScrollingStarted(WheelView wheel) {

        }

        @Override
        public void onScrollingFinished(WheelView wheel) {
            int newValue = year.getCurrentItem();
            int intYear = ((NumericWheelAdapter) year.getViewAdapter()).getValue(newValue);
            int intMonth = ((NumericWheelAdapter) wheel.getViewAdapter()).getValue(month.getCurrentItem());
            refreshDays(intYear, intMonth);
        }
    }
}
